const kurento = require("kurento-client");
var mqtt = require('mqtt');
var path = require('path');
var fs = require('fs');
var format = require('string-format');
const e = require("express");
format.extend(String.prototype);

class TKms {
    constructor() {
        this.config = {
            kmsUrl: "wss://wss.hhdata.cn:8433/kurento",
            tagKey: "tagKey-kms"
        }
        this.kmsObjs = {};
        this.kmsObjsKey = {};
        this.tasks = [{
            key: "app01",
            code: "app01",
            name: "德清急救",
            objType: "app",
            kmsType: "MediaPipeline",
            kmsId: ""
        }, {
            key: "app01/g01",
            code: "g01",
            name: "浙E14563",
            objType: "group",
            kmsType: "Dispatcher",
            kmsId: ""
        }, {
            key: "app01/g01/r01",
            code: "r01",
            name: "医院急诊室",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r02",
            code: "r01",
            name: "医院胸痛中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r03",
            code: "r02",
            name: "医院卒中中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r03",
            code: "r03",
            name: "医院卒中中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r04",
            code: "r04",
            name: "医院创伤中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r05",
            code: "r05",
            name: "司机",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r06",
            code: "r06",
            name: "后舱",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r07",
            code: "r07",
            name: "生命体征",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g01/r08",
            code: "r08",
            name: "交警",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02",
            code: "g02",
            name: "浙E73523",
            objType: "group",
            kmsType: "Dispatcher",
            kmsId: ""
        }, {
            key: "app01/g02/r01",
            code: "r01",
            name: "医院急诊室",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r02",
            code: "r01",
            name: "医院胸痛中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r03",
            code: "r02",
            name: "医院卒中中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r03",
            code: "r03",
            name: "医院卒中中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r04",
            code: "r04",
            name: "医院创伤中心",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r05",
            code: "r05",
            name: "司机",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r06",
            code: "r06",
            name: "后舱",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r07",
            code: "r07",
            name: "生命体征",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }, {
            key: "app01/g02/r08",
            code: "r08",
            name: "交警",
            objType: "role",
            kmsType: "Hubport",
            kmsId: ""
        }];
        this.kmsClient = undefined;
    }

    getClient() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.kmsClient && me.kmsClient != null) {
                    success(me.kmsClient);
                } else {
                    kurento(me.config.kmsUrl, function(erClient, _client) {
                        me.kmsClient = _client;
                        _client.on('disconnect', function() {
                            delete me["kmsClient"];
                        })
                        _client.getServerManager().then(_svr => {
                            _client.svr = _svr;
                            _svr.on('ObjectDestroyed', (data => {
                                me.saveLog('ObjectDestroyed', me.kmsObjs[data.objectId]);
                                if (me.kmsObjs[data.objectId]) {
                                    delete me.kmsObjs[data.objectId];
                                }
                            }));
                            success(me.kmsClient);
                        })
                    })
                }
            } catch (er) {
                console.log(er);
                success();
            }
        })
    }
    getKmsObjs() {
        var me = this;
        var objs = []
        return new Promise((success, faild) => {
            try {
                me.kmsObjs = {};
                me.kmsObjsKey = {};
                var appendObj = function(obj) {
                    return new Promise((s, f) => {
                        obj.getTags().then(tags => {
                            var arr = tags.filter(t => {
                                return t.key == me.config.tagKey;
                            });
                            if (arr.length > 0) {
                                me.kmsObjs[obj.id] = obj;
                                var infoJson = arr[0].value;
                                var info = JSON.parse(infoJson);
                                info.kmsId = obj.id;
                                var ids = obj.id.split(".");
                                info.kmsType = ids[ids.length - 1];
                                obj.info = info;
                                me.kmsObjsKey[obj.info.key] = obj;
                                obj.getChildren().then(items => {
                                    var loadItem = function() {
                                        if (items.length > 0) {
                                            var item = items.shift();
                                            appendObj(item).then(_ => {
                                                loadItem();
                                            });
                                        } else {
                                            s();
                                        }
                                    }
                                    loadItem();
                                })
                            } else {
                                s();
                            }
                        })
                    });
                }

                me.getClient().then(client => {
                    return client.svr.getPipelines();
                }).then(ps => {
                    var loadPipes = function() {
                        if (ps.length > 0) {
                            var p = ps.shift();
                            appendObj(p).then(_ => {
                                loadPipes();
                            })
                        } else {
                            success();
                        }
                    }
                    loadPipes();
                });
            } catch (er) {
                console.log(er);
                success(objs);
            }
        })
    }
    loadKmsObjs() {
        var me = this;
        var res = []
        return new Promise((success, faild) => {
            try {
                me.getKmsObjs().then(_ => {
                    var items = [];
                    me.tasks.forEach(k => {
                        items.push(k);
                    })
                    var createNewObj = function(task) {
                        return new Promise((s, f) => {
                            var setInfo = (obj) => {
                                var infoJson = JSON.stringify(task);
                                obj.addTag(me.config.tagKey, infoJson).then(_ => {
                                    obj.info = task;
                                    obj.info.kmsId = obj.id;
                                    me.kmsObjs[obj.id] = obj;
                                    me.kmsObjsKey[task.key] = obj;
                                    s();
                                })
                            }
                            if (task.kmsType == "MediaPipeline") {
                                me.kmsClient.create("MediaPipeline").then(pipe => {
                                    setInfo(pipe);
                                })
                            } else if (task.kmsType == "Dispatcher") {
                                var keys = task.key.split("/");
                                var pipeKey = keys[0];
                                var pipe = me.kmsObjsKey[pipeKey];
                                if (pipe && pipe != null) {
                                    pipe.create("Dispatcher").then(hub => {
                                        setInfo(hub);
                                    })
                                }
                            } else if (task.kmsType == "Hubport") {
                                var keys = task.key.split("/");
                                var hubKey = [keys[0], keys[1]].join("/");
                                var hub = me.kmsObjsKey[hubKey];
                                if (hub && hub != null) {
                                    hub.createHubPort().then(hubport => {
                                        setInfo(hubport);
                                    })
                                }
                            } else {
                                s();
                            }
                        })
                    }
                    var loadItem = function() {
                        if (items.length > 0) {
                            var item = items.shift();
                            var obj = me.kmsObjsKey[item.key];
                            if (obj && obj != null) {
                                item.kmsId = obj.info.kmsId;
                                item.kmsType = obj.info.kmsType;
                                loadItem();
                            } else {
                                createNewObj(item).then(_ => {
                                    loadItem();
                                });
                            }
                        } else {
                            success();
                        }
                    }
                    loadItem();
                })
            } catch (er) {
                console.log(er);
                success(res);
            }
        })
    }
}

var k = new TKms();
k.loadKmsObjs().then(_ => {
    console.log(k.kmsObjsKey);
})